
package com.skytech.tax.customsdatawarehouse.fta.origincredential.domain.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.tax.customsdatawarehouse.common.util.SecurityUtil;
import com.skytech.tax.customsdatawarehouse.fta.origincredential.domain.dao.FtaOriginCredentialRepository;
import com.skytech.tax.customsdatawarehouse.fta.origincredential.domain.entity.FtaOriginCredential;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FtaOriginCredentialService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FtaOriginCredentialService.class);

    @Value("${customsdatawarehouse.token}")
    private String token;

    @Resource
    private FtaOriginCredentialRepository federatedOriginCredentialRepository;


    public void save(String originCredentials) {
        if (StringUtils.isEmpty(originCredentials)) return;
        String originCredentialsText = SecurityUtil.decrypt3DES(token, originCredentials);
        try {
            JSONObject data = JSON.parseObject(originCredentialsText);
            if (data == null) return;
            String socialCreditCode = data.getString("socialCreditCode");
            JSONArray originCredentialArr = data.getJSONArray("originCredentials");
            if (CollectionUtils.isEmpty(originCredentialArr)) return;

            List<FtaOriginCredential> ftaOriginCredentialList = new ArrayList<>();
            for (int i = 0; i < originCredentialArr.size(); i++) {
                JSONObject item = originCredentialArr.getJSONObject(i);
                ftaOriginCredentialList.add(new FtaOriginCredential(socialCreditCode, item));
            }
            if (CollectionUtils.isEmpty(ftaOriginCredentialList)) return;

            federatedOriginCredentialRepository.deleteBy(ftaOriginCredentialList.stream().map(FtaOriginCredential::getId).collect(Collectors.toList()));

            federatedOriginCredentialRepository.save(ftaOriginCredentialList);
        } catch (Exception e) {
            LOGGER.error("保存fta原产地证书错误", e);
        }
    }
}
